package com.example.xutildemoproject.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.example.xutildemoproject.R;
import com.xuexiang.constant.MimeTypeConstants;
import com.xuexiang.constant.PermissionConstants;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xutil.app.IntentUtils;
import com.xuexiang.xutil.app.PathUtils;
import com.xuexiang.xutil.app.SAFUtils;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.file.FileUtils;
import com.xuexiang.xutil.resource.ResourceUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yalantis.ucrop.util.MimeType;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

import butterknife.BindView;
import butterknife.OnClick;

@Page(name = "SAFUtils测试")
public class SAFFragment extends XPageFragment {
    public static final int REQUEST_FILE = 1000;

    @BindView(R.id.tv_mode)
    TextView tvMode;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_operation)
    TextView tvOperation;
    @BindView(R.id.iv_content)
    AppCompatImageView ivContent;

    private String mFilePath;
    private Uri mUri;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saf_utils;
    }

    @Override
    protected void initViews() {
        tvMode.setText("当前是否是兼容模式运行:" + SAFUtils.isExternalStorageLegacy());
        tvOperation.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    @Override
    protected void initListeners() {

    }

    @SingleClick
    @OnClick({R.id.btn_select,R.id.btn_write,R.id.btn_read,R.id.btn_write_any,
            R.id.btn_read_image,R.id.btn_write_image,R.id.btn_md5})
    protected void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.btn_select:
                selectFile();
                break;
            case R.id.btn_write:
                writeFile();
                break;
            case R.id.btn_read:
                readFile();
                break;
            case R.id.btn_write_any:
                writeAny();
                break;
            case R.id.btn_read_image:
                readImage();
                break;
            case R.id.btn_write_image:
                saveImage();
                break;
            case R.id.btn_md5:
                getMD5();
                break;
            default:
                break;
        }
    }

    private void getMD5() {
        if (!isSelectFile()) {
            ToastUtils.toast("请选择一个图片文件");
            return;
        }
        String md5String = FileUtils.getFileMD5ToString(mFilePath);
        tvContent.setText(md5String);
    }

    @IOThread
    private void saveImage() {
        if (!isSelectFile()) {
            ToastUtils.toast("请选择一个图片文件");
            return;
        }
        if (!mFilePath.endsWith(".jpg") && !mFilePath.endsWith(".png")) {
            ToastUtils.toast("请选择jpg或者png格式的图片文件");
            return;
        }
        Bitmap bitmap = ImageUtils.getBitmap(SAFUtils.openInputStream(mUri));
        String path = "test_image" + File.separator;
        String name = DateUtils.getNowString(DateUtils.yyyyMMddHHmmssNoSep.get()) + ".jpg";
        Log.e("path",Paths.get(path,name).toString());
        if (SAFUtils.saveImageToPublicDCIM(path,name,bitmap, Bitmap.CompressFormat.JPEG)) {
            ToastUtils.toast("图片写入成功");
        }else{
            ToastUtils.toast("图片写入失败");
        }
    }

    @IOThread
    @Permission(PermissionConstants.STORAGE)
    private void readImage() {
        if (!isSelectFile()) {
            ToastUtils.toast("请选择文件");
            return;
        }
        if (!mFilePath.endsWith(".jpg") && !mFilePath.endsWith(".png")) {
            ToastUtils.toast("请选择jpg或者png格式的文件");
            return;
        }
        Bitmap bitmap = ImageUtils.getBitmap(SAFUtils.openInputStream(mUri));
        if (bitmap != null) {
            ivContent.setImageBitmap(bitmap);
        }
    }

    @Permission(PermissionConstants.STORAGE)
    private void writeAny() {
        InputStream inputStream = ResourceUtils.openAssetsFile("test.txt");
        String path = PathUtils.getExtDownloadsPath() + File.separator + "test" + File.separator;
        String name = DateUtils.getNowString(DateUtils.yyyyMMddHHmmssNoSep.get()) + ".txt";
        if (SAFUtils.writeFileAny(path,name, MimeTypeConstants.TXT,inputStream)) {
            ToastUtils.toast("文件写入成功");
        }else{
            ToastUtils.toast("文件写入失败");
        }
    }

    @IOThread
    @Permission(PermissionConstants.STORAGE)
    private void writeFile(){
        try {
            InputStream inputStream = ResourceUtils.openAssetsFile("test.txt");
            String path = "test" + File.separator;
            String name = DateUtils.getNowString(DateUtils.yyyyMMddHHmmssNoSep.get()) + ".txt";
            Log.e("path",Paths.get(path,name).getFileName().toString());
            if (SAFUtils.writeFileToPublicDownloads(path,name, MimeTypeConstants.TXT,inputStream)) {
                ToastUtils.toast("文件写入成功");
            }else{
                ToastUtils.toast("文件写入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isSelectFile(){
        return mFilePath != null && FileUtils.isFileExists(mFilePath);
    }
    @IOThread
    @Permission(PermissionConstants.STORAGE)
    private void readFile(){
        if (!isSelectFile()) {
            ToastUtils.toast("请选择文件");
            return;
        }
        if (!mFilePath.endsWith(".txt")) {
            ToastUtils.toast("请选择txt文件");
            return;
        }
        String content = ResourceUtils.readInputStream(SAFUtils.openInputStream(mUri),true);
        tvOperation.setText(content);
    }
    @Permission(PermissionConstants.STORAGE)
    private void selectFile(){
        startActivityForResult(IntentUtils.getDocumentPickerIntent(IntentUtils.DocumentType.ANY),REQUEST_FILE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_FILE) {
                if (data != null) {
                    mUri = data.getData();
                    mFilePath = PathUtils.getFilePathByUri(mUri);
                    String result = mFilePath;
                    if (result == null) {
                        result = "解析文件失败";
                    }else{
                        result = "文件路径:" + mFilePath;
                    }
                    tvContent.setText(result);
                }
            }
        }
    }
}
